using System;
using System.Threading;

using Microsoft.SPOT;

using mfRCF.Core;
using mfRCF.Core.Extensions;

using mfXmlSerializer;

using mfLogger;

using OST.Shared.SharedTypes;
using OST.Persistence;
using OST.Shared;
using OST.Motor;
using OST.Commands.Extensions;

namespace OST.Commands
{

    /// <summary>
    /// (re-) initiates the motor
    /// </summary>
    public class MotorInitGETCommand : mfRcfCommand
    {
        #region CTOR

        public MotorInitGETCommand(string httpPath)
            : base(httpPath, new mfGETMethod())
        {
        }

        #endregion

        #region mfRcfCommand
        public override void ExecuteCommand(mfIHttpContext httpContext)
        {
            if (!MotorProvider.Instance.HasInstance)
                this.WriteHttpResponseError(httpContext, new OSTException("no motor-instance available"));

            var motor = MotorProvider.Instance.MotorInstance;
            try
            {
                //init motor async
                var thread = new Thread(new ThreadStart(InitMotorAsync));
                thread.Start();

                this.WriteHttpResponseOK(httpContext, "motor initialization started");
            }
            catch (Exception ex)
            {
                this.WriteHttpResponseError(httpContext, ex);
            }
        }

        public void InitMotorAsync()
        {
            Thread.Sleep(MotorProvider.Instance.MotorInstance.MotorConfig.Wait);
            //(re-)initialize the motor
            MotorProvider.Instance.MotorInstance.Initialize();
        }

        #endregion
    }
}
